﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Serialization;

namespace ClassLibrary1.entity
{
    [Serializable]
   // [XmlRoot("driver")]
    public class Driver:BaseEntity
    {
        [XmlIgnore]
        public Car car { get; set; }

        //[XmlElement("name")]
        public string name { get; set; }

        public Driver()
        {
            int id = 1;

            while (true)
            {
                var entity = FindById(id.ToString());
                if (entity == null)
                {
                    this.id = id;
                    return;
                }
                id++;
            }
        }

        public Driver(string id)
        {
            if (Driver.FindById(id) != null) return;
            int.TryParse(id, out this.id);
        }

       public Driver(string[] mas)
       {
           this.id = Convert.ToInt32(mas[0]);
           Upd(mas.Skip(1).ToArray());
       }

        public static Driver FindById(string id)
        {
            return (Driver)Data.entity.FirstOrDefault(item => item.GetType() == typeof(Driver) && item.id == int.Parse(id));
        }

        public static List<BaseEntity> FindAll()
        {
            return Data.entity.FindAll(item => item.GetType() == typeof(Driver));
        }

        public override void Upd(string[] mas)
        {
            try { this.name = mas[0]; }
            catch (Exception) { }
            try { 
                this.car = Car.FindById(mas[1]);
                if (this.car != null) this.car.driver = this;
            }
            catch (Exception) { }
        }

        public bool Equals(Booking a)
        {
            if (this.id.Equals(a.id)) return true;
            return false;
        }

        public override string Write()
        {
            string s = "driver" + " " + this.id;
            s += " ";
            if (this.name != null && this.name.Trim() != "") s += this.name.ToString();
            s += " ";
            if (this.car != null) s += this.car.id.ToString();
            return s;
        }
    }
}
